//
//  Helper.m
//  PalmKitchen
//
//  Created by apple on 14-10-14.
//  Copyright (c) 2014年 apple. All rights reserved.
//

#import "Helper.h"
#import <CommonCrypto/CommonCrypto.h>
#import <AVFoundation/AVFoundation.h>
#import "sys/utsname.h"

@implementation Helper


/**
 创建按钮就字体为16的

 @param frame 位置
 @param title tittle
 @param imgName 图片
 @param target
 @param selector action
 @return button
 */
+ (UIButton *)createBBI:(CGRect)frame title:(NSString *)title image:(NSString *)imgName target:(id)target selector:(SEL)selector
{
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = frame;
    [button setBackgroundImage:[UIImage imageNamed:imgName] forState:UIControlStateNormal];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    button.titleLabel.font = [UIFont systemFontOfSize:16];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    
    return button;
}

/**
 创建按钮就字体为14的
 
 @param frame 位置
 @param title tittle
 @param imgName 图片
 @param target
 @param selector action
 @return button
 */
+(UIButton *)createButton:(CGRect)frame title:(NSString *)title image:(UIImage *)image target:(id)target selector:(SEL)selector
{
    UIButton * button=[UIButton buttonWithType:UIButtonTypeCustom];
//    [button setImage:image forState:UIControlStateNormal];
    [button setBackgroundImage:image forState:UIControlStateNormal];
    button.frame=frame;
    button.titleLabel.font = [UIFont systemFontOfSize:14];
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    
//    CGRect newFrame=frame;
//    newFrame.origin.y=frame.size.height/2.0;
//    newFrame.size.height=frame.size.height/2.0;
//    newFrame.origin.x=0;
//    UILabel * label=[[UILabel alloc]initWithFrame:newFrame];
//    label.text=title;
//    [button addSubview:label];
//    label.font=[UIFont systemFontOfSize:12];
//    label.backgroundColor=[UIColor clearColor];
    [button addTarget:target action:selector forControlEvents:UIControlEventTouchUpInside];
    return button;
}

/**
 根据文字大小高度获取宽度

 @param string 文字内容
 @param font 字体大小
 @param height 高度
 @return 宽度
 */
+(CGFloat)widthOfString:(NSString *)string font:(UIFont *)font height:(CGFloat)height
{
    NSDictionary * dict=[NSDictionary dictionaryWithObject: font forKey:NSFontAttributeName];
    CGRect rect=[string boundingRectWithSize:CGSizeMake(CGFLOAT_MAX, height) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
    return rect.size.width;
}
/**
 根据文字大小宽度度获取高度
 
 @param string 文字内容
 @param font 字体大小
 @param width 宽度
 @return 高度
 */
+(CGFloat)heightOfString:(NSString *)string font:(UIFont *)font width:(CGFloat)width
{
    CGRect bounds;
    NSDictionary * parameterDict=[NSDictionary dictionaryWithObject:font forKey:NSFontAttributeName];
    bounds=[string boundingRectWithSize:CGSizeMake(width, CGFLOAT_MAX) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:parameterDict context:nil];
    return bounds.size.height;
}


/**
 获取当天的日期：年月日

 @return
 */
+ (NSDictionary *)getTodayDate
{
    //获取今天的日期
    NSDate *today = [NSDate date];
    
    // 日历类
    NSCalendar *calendar = [NSCalendar currentCalendar];
    
    // 日历构成的格式
    NSCalendarUnit unit = kCFCalendarUnitYear|kCFCalendarUnitMonth|kCFCalendarUnitDay;
    
    // 获取对应的时间点
    NSDateComponents *components = [calendar components:unit fromDate:today];
    
    NSString *year = [NSString stringWithFormat:@"%ld", (long)[components year]];
    NSString *month = [NSString stringWithFormat:@"%02ld", (long)[components month]];
    NSString *day = [NSString stringWithFormat:@"%02ld", (long)[components day]];
    
    NSMutableDictionary *todayDic = [[NSMutableDictionary alloc] init];
    [todayDic setObject:year forKey:@"year"];
    [todayDic setObject:month forKey:@"month"];
    [todayDic setObject:day forKey:@"day"];
    
    return todayDic;
}

/**
 //  颜色转换为背景图片
 
 @param color UIColor
 @return UIImage
 */
+ (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    return image;
}

/**
 两时间比较

 @param from 起始时间
 @param to 结束时间
 @return 剩余%ld小时%ld分钟
 */
+(NSString *)compareFromDate:(NSDate *)from toDate:(NSDate *)to
{
    if (!to || !from) {
        return @"";
    }
    
    // 日历
    NSCalendar * calendar = [NSCalendar currentCalendar];
    
    // 时间片段 ：年  月  日  时 分 秒
    int unit = NSCalendarUnitYear | NSCalendarUnitMonth  | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    
    NSDateComponents * com = [calendar components:unit fromDate:from toDate:to options:0];
    
    NSString *string = [NSString stringWithFormat:@"剩余%ld小时%ld分钟", (long)com.hour, (long)com.minute];
    
    return string;
}




/**
 //邮箱验证

 @param email email
 @return bool
 */
+ (BOOL)justEmail:(NSString *)email
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:email];
}



/**
 //手机号码验证

 @param mobile 手机号
 @return bool
 */
+ (BOOL)justMobile:(NSString *)mobile
{
    //手机号以13，17， 15，18开头，八个 \d 数字字符
    NSString *phoneRegex = @"^((13[0-9])|(17[0-9])|(15[^4,\\D])|(18[0,0-9]))\\d{8}$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:mobile];
}



/**
 //车牌号验证

 @param carNo //车牌号
 @return bool
 */
+ (BOOL)justCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}



/**
 //车型

 @param CarType //车型
 @return bool
 */
+ (BOOL)justCarType:(NSString *)CarType
{
    NSString *CarTypeRegex = @"^[\u4E00-\u9FFF]+$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",CarTypeRegex];
    return [carTest evaluateWithObject:CarType];
}


/**
 //用户名

 @param name name
 @return bool
 */
+ (BOOL)justUserName:(NSString *)name
{
    NSString *userNameRegex = @"^[A-Za-z0-9]{6,20}+$";
    NSPredicate *userNamePredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",userNameRegex];
    BOOL B = [userNamePredicate evaluateWithObject:name];
    return B;
}


/**
 //密码

 @param passWord //密码
 @return bool
 */
+ (BOOL)justPassword:(NSString *)passWord
{
    NSString *passWordRegex = @"^[a-zA-Z0-9]{6,20}+$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passWordRegex];
    return [passWordPredicate evaluateWithObject:passWord];
}


/**
 //昵称

 @param nickname //昵称
 @return bool
 */
+ (BOOL)justNickname:(NSString *)nickname
{
    NSString *nicknameRegex = @"^[\u4e00-\u9fa5]{4,8}$";
    NSPredicate *passWordPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",nicknameRegex];
    return [passWordPredicate evaluateWithObject:nickname];
}


/**
 //身份证号验证

 @param identityCard 身份证号
 @return bool
 */
+ (BOOL)justIdentityCard: (NSString *)identityCard
{
    BOOL flag;
    if (identityCard.length <= 0) {
        flag = NO;
        return flag;
    }
    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    return [identityCardPredicate evaluateWithObject:identityCard];
}

/**
 转换成MD5.32位小写
 
 @param string string description
 @return <#return value description#>
 */
+ (NSString *)md5SmallString:(NSString *)string
{
    //32位小写
    const char *str = [string UTF8String];
    unsigned char r[CC_MD5_DIGEST_LENGTH];
    CC_MD5(str, (CC_LONG)strlen(str), r);
    
    return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
            r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
    
}
/**
 转换成MD5.32位大写

 @param string <#string description#>
 @return <#return value description#>
 */
+ (NSString *)md5String:(NSString *)string
{
    
    
//大写
    const char *cStr = [string UTF8String];
       unsigned char result[16];
        CC_MD5( cStr, (CC_LONG)strlen(cStr), result );
        return [NSString stringWithFormat:
                    @"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3],
            result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],
            result[12], result[13], result[14], result[15]
            ];
}



/**
 根据rgb获取颜色

 @param red
 @param green
 @param blue
 @param alpha
 @return UIColor
 */
+(UIColor *)colorWithRed:(NSInteger)red green:(NSInteger)green blue:(NSInteger)blue alpha:(NSInteger)alpha
{
    return [UIColor colorWithRed:red/255.0 green:green/255.0 blue:blue/255.0 alpha:alpha];
}

/**
 //16进制颜色转UIColor
 
 @param color 16进制颜色
 @return UIColor
 */
+ (UIColor *) colorWithHexString: (NSString *)color
{
    NSString *cString = [[color stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    
    // String should be 6 or 8 characters
    if ([cString length] < 6) {
        return [UIColor clearColor];
    }
    // 判断前缀
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor clearColor];
    // 从六位数值中找到RGB对应的位数并转换
    NSRange range;
    range.location = 0;
    range.length = 2;
    //R、G、B
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f) alpha:1.0f];
}



/**
 //token失效自动登录

 @return <#return value description#>
 */
//+(NSString *)automaticLogin
//{
    
//   NSString *telNum = [[NSUserDefaults standardUserDefaults]objectForKey:@"TelNum"];
//    NSString *userPwd = [[NSUserDefaults standardUserDefaults]objectForKey:@"UserPwd"];
//    NSDictionary *dic = @{@"UserName":telNum,@"Password":userPwd,@"UserId":@"",@"Version":@""};
//    __block NSString *tipString = @"000" ;
//
//    UIWindow *window = [UIApplication sharedApplication].windows[0];
//    [window makeKeyAndVisible];
//    //关闭等待提示
//    [MBProgressHUD hideHUDForView:window animated:YES];
//    //显示正在加载
//    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:window animated:YES];
//    //        hud.mode = MBProgressHUDModeCustomView; //设置样式
//    hud.label.text = @"登录已失效";
//    hud.detailsLabel.text = @"重新授权中...";
//
//    [YDHttpRequest POST:URL_LOGIN parmaters:dic success:^(id responseObject) {
//
//        //关闭等待提示
//        [MBProgressHUD hideHUDForView:window animated:YES];
//
//            tipString = @"自动登录成功";
//
//        //保存登录者信息
//        if (![responseObject[@"CompanyName"] isEqual:[NSNull null]]) {
//            //公司
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"CompanyName"] forKey:@"CompanyName"];
//        }else
//        {
//            //公司
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"CompanyName"];
//        }
//
//        if (![responseObject[@"CompanyId"] isEqual:[NSNull null]]) {
//            //公司id
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"CompanyId"] forKey:@"CompanyId"];
//        }else
//        {
//            //公司id
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"CompanyId"];
//        }
//
//
//        if (![responseObject[@"DepartmentID"] isEqual:[NSNull null]]) {
//            //部门id
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"DepartmentID"] forKey:@"DepartmentID"];
//        }else
//        {
//            //部门id
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"DepartmentID"];
//        }
//
//        //生日
//        if (![responseObject[@"Dirthday"] isEqual:[NSNull null]]) {
//
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"Dirthday"] forKey:@"Dirthday"];
//        }else
//        {
//
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"Dirthday"];
//        }
//
//        //性别
//        if (![responseObject[@"Sex"] isEqual:[NSNull null]]) {
//
//            [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@",responseObject[@"Sex"]] forKey:@"Sex"];
//        }else
//        {
//
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"Sex"];
//        }
//
//
//        //个性签名
//        if (![responseObject[@"Signature"] isEqual:[NSNull null]]) {
//
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"Signature"] forKey:@"Signature"];
//        }else
//        {
//
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"Signature"];
//        }
//
//
//        //我的积分
//        if (![responseObject[@"RewarePoints"] isEqual:[NSNull null]]) {
//
//            [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@",responseObject[@"RewarePoints"]] forKey:@"RewarePoints"];
//        }else
//        {
//
//            [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"RewarePoints"];
//        }
//
//
//        //是否公开电话
//        if (![responseObject[@"isPublicTel"] isEqual:[NSNull null]]) {
//
//            [[NSUserDefaults standardUserDefaults]setObject:[NSString stringWithFormat:@"%@",responseObject[@"isPublicTel"]] forKey:@"isPublicTel"];
//        }else
//        {
//
//            [[NSUserDefaults standardUserDefaults]setObject:@"0" forKey:@"isPublicTel"];
//        }
//
//
//
//        if (![responseObject[@"DepartmentName"] isEqual:[NSNull null]]) {
//            //部门
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"DepartmentName"] forKey:@"DepartmentName"];
//        }else
//        {
//            //部门
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"DepartmentName"];
//        }
//        if (![responseObject[@"Position"] isEqual:[NSNull null]]) {
//            //部门，职位
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"Position"] forKey:@"Position"];
//        }else
//        {
//            //部门，职位
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"Position"];
//        }
//        if (![responseObject[@"RealName"] isEqual:[NSNull null]]) {
//            //姓名
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"RealName"] forKey:@"RealName"];
//        }else
//        {
//            //姓名
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"RealName"];
//        }
//        if (![responseObject[@"UserPwd"] isEqual:[NSNull null]]) {
//            //密码
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"UserPwd"] forKey:@"UserPwd"];
//        }else
//        {
//            //密码
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"UserPwd"];
//        }
//        if (![responseObject[@"TelNum"] isEqual:[NSNull null]]) {
//            //电话
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"TelNum"] forKey:@"TelNum"];
//        }else
//        {
//            //电话
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"TelNum"];
//        }
//        if (![responseObject[@"UserAvaterUrl"] isEqual:[NSNull null]]) {
//            //头像地址
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"UserAvaterUrl"] forKey:@"UserAvaterPath"];
//        }else
//        {
//            //头像地址
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"UserAvaterPath"];
//        }
//        if (![responseObject[@"access_token"] isEqual:[NSNull null]]) {
//            //access_token
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"access_token"] forKey:@"access_token"];
//        }else
//        {
//            //access_token
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"access_token"];
//        }
//        if (![responseObject[@"expires_in"] isEqual:[NSNull null]]) {
//            //expires_in
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"expires_in"] forKey:@"expires_in"];
//        }
//        else
//        {
//            //expires_in
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"expires_in"];
//        }
//        if (![responseObject[@"token_type"] isEqual:[NSNull null]]) {
//            //token_type
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"token_type"] forKey:@"token_type"];
//        }else
//        {
//            //token_type
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"token_type"];
//        }
//        if (![responseObject[@"UserId"] isEqual:[NSNull null]]) {
//            //UserId
//            [[NSUserDefaults standardUserDefaults]setObject:responseObject[@"UserId"] forKey:@"UserId"];
//        }else
//        {
//            //UserId
//            [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"UserId"];
//        }
//
//        [[NSUserDefaults standardUserDefaults]synchronize];
//
//        // postNotification 发起一个通知
//        // 参数1: 通知的名称（接收通知时也需要这个名称）
//        // 参数2: 传出的参数
////        [[NSNotificationCenter defaultCenter] postNotificationName:@"automaticLogin" object:tipString];
//
//        YDMycustomLab *tipLab = [YDMycustomLab new];
//        tipLab.title = tipString;
//
//        } failure:^(NSError *error) {
//
//            //关闭等待提示
//            [MBProgressHUD hideHUDForView:window animated:YES];
//
//            [self errorTipError:error];
//
//
//        }];
//
//
//                  return tipString;
//}



/**
 //将十六进制的字符串转换成NSString则可使用如下方式:

 @param str 16进制字符串
 @return 字符串
 */
+ (NSString *)convertHexStrToString:(NSString *)str {
    if (!str || [str length] == 0) {
        return nil;
    }
    
    NSMutableData *hexData = [[NSMutableData alloc] initWithCapacity:8];
    NSRange range;
    if ([str length] % 2 == 0) {
        range = NSMakeRange(0, 2);
    } else {
        range = NSMakeRange(0, 1);
    }
    for (NSInteger i = range.location; i < [str length]; i += 2) {
        unsigned int anInt;
        NSString *hexCharStr = [str substringWithRange:range];
        NSScanner *scanner = [[NSScanner alloc] initWithString:hexCharStr];
        
        [scanner scanHexInt:&anInt];
        NSData *entity = [[NSData alloc] initWithBytes:&anInt length:1];
        [hexData appendData:entity];
        
        range.location += range.length;
        range.length = 2;
    }
    NSString *string = [[NSString alloc]initWithData:hexData encoding:NSUTF8StringEncoding];
    return string;
}


/**
 //将NSString转换成十六进制的字符串则可使用如下方式:

 @param str NSString
 @return 十六进制的字符串
 */
+ (NSString *)convertStringToHexStr:(NSString *)str {
    if (!str || [str length] == 0) {
        return @"";
    }
    NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
    
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}


/**
 //一直遍历视图的父视图,找他的响应者.如果响应者是视图控制器,则返回它.

 @param view 子视图
 @return 子视图的控制器
 */
+ (UIViewController *)view:(UIView *)view
{
    for (UIView* next = [view superview]; next; next = next.superview)
    {
        UIResponder *nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[UIViewController class]])
        {
            return (UIViewController *)nextResponder;
        }
    }
    return nil;
}


/**
 //修改文件名

 @param folderName 修改的文件名
 @param beforeName 愿的文件名
 */
+ (void)changeFolderName:(NSString *)folderName beforeName:(NSString *)beforeName {
    NSFileManager *fm = [NSFileManager defaultManager];
//    NSString *beforeFolder = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(),beforeName];
//    NSString *afterFolder = [NSString stringWithFormat:@"%@/Documents/%@", NSHomeDirectory(),folderName];
    [fm createDirectoryAtPath:folderName withIntermediateDirectories:YES attributes:nil error:nil];
    NSDirectoryEnumerator *dirEnum = [fm enumeratorAtPath:beforeName];
    NSString *path;
    while ((path = [dirEnum nextObject]) != nil) {
        [fm moveItemAtPath:[NSString stringWithFormat:@"%@/%@",beforeName,path]
                    toPath:[NSString stringWithFormat:@"%@/%@",folderName,path]
                     error:NULL];
    }
    [fm removeItemAtPath:beforeName error:nil];
}




/**
 //读取CSV文件的数据utf8格式

 @param fileName CSV文件名
 @return NSMutableArrayCSV内容
 */
+(NSMutableArray *)readCSVDataWithFileName:(NSString *)fileName
{
    NSMutableArray *_InfoArray;
    if (_InfoArray) {
        return NULL;
    }
    _InfoArray=[[NSMutableArray alloc]init];
    
    NSString *filepath=[[NSBundle mainBundle] pathForResource:fileName ofType:@"csv"];
    
    
    
    FILE *fp=fopen([filepath UTF8String], "r");
    if (fp) {
        char buf[BUFSIZ];
        fgets(buf, BUFSIZ, fp);
        while (!feof(fp)) {
            char buf[BUFSIZ];
            fgets(buf, BUFSIZ, fp);
            
            

            // 处理文本信息 转化 成 数组文件
            NSString *s=[[NSString alloc]initWithUTF8String:(const char *)buf];
            

            NSString *ss=[s stringByReplacingOccurrencesOfString:@"\r" withString:@""];
            ss=[ss stringByReplacingOccurrencesOfString:@"\n" withString:@""];
            ss =  [ss stringByReplacingOccurrencesOfString:@"\"" withString:@""];

            NSArray *a=[ss componentsSeparatedByString:@","];
            
            if (a && a.count > 0) {
                [_InfoArray addObject:a];
            }
            
        }
    }
    [_InfoArray removeLastObject];
    
    NSLog(@"%@",_InfoArray);
    return _InfoArray;
}


/**
 //读取CSV文件的数据GB_18030_2000格式

 @param fileName CSV文件名
 @return NSMutableArrayCSV内容
 */
+(NSMutableArray *)readGB_18030_2000CSVDataWithFileName:(NSString *)fileName
{
    
    NSMutableArray *_InfoArray;
    if (_InfoArray) {
        return NULL;
    }
    _InfoArray=[[NSMutableArray alloc]init];

    NSString *path = [[NSBundle mainBundle]pathForResource:fileName ofType:@"csv"];
    
    NSLog(@"%@",path);
    
    NSError *error = nil;
    unsigned long encode = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    
    NSString *fileContents = [NSString stringWithContentsOfFile:path encoding:encode error:&error];
    //取出每一行的数据
    NSArray *_allLinedStrings = [fileContents componentsSeparatedByString:@"\r\n"];
    
    
    
    for (NSString *string in _allLinedStrings) {
        NSString *ss=[string stringByReplacingOccurrencesOfString:@"\r" withString:@""];
        ss=[ss stringByReplacingOccurrencesOfString:@"\n" withString:@""];
        ss =  [ss stringByReplacingOccurrencesOfString:@"\"" withString:@""];
        
        NSArray *a=[ss componentsSeparatedByString:@","];
        
        if (a && a.count > 0) {
            [_InfoArray addObject:a];
        }

    }
    
    return _InfoArray;

}


/**
 //图像压缩成指定大小（高度/宽度）

 @param targetSize 指定大小
 @param image UIImage
 @return UIImage
 */
+ (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize image:(UIImage *)image
{
    
    UIImage *sourceImage = image;
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth= width * scaleFactor;
        
        scaledHeight = height * scaleFactor;
        
        // center the image
        
        if (widthFactor > heightFactor)
            
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else if (widthFactor < heightFactor)
        {
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
        
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width= scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
        
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}




/**
 //接口地址含有中文的转码处理

 @param url url
 @return NSString
 */
+(NSString *)ChineseUrlForUT8Url:(NSString *)url
{

    return [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}


/**
 时间转时间
 
 @param time1 时间1
 @param type1 时间1格式
 @param type2 时间2格式
 @return 时间2
 */
+(NSString *)timeWithTime1:(NSString *)time1 timeType1:(NSString *)type1 timeType2:(NSString *)type2;
{
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init] ;
    [formatter1 setDateStyle:NSDateFormatterMediumStyle];
    [formatter1 setTimeStyle:NSDateFormatterShortStyle];
    [formatter1 setDateFormat:type1]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter1 setTimeZone:timeZone];
    
    NSDate* date = [formatter1 dateFromString:time1]; //------------将字符串按formatter转成nsdate
    
    //    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    //
    //    NSString *nowtimeStr = [formatter stringFromDate:datenow];//----------将nsdate按formatter格式转成nsstring
    //    时间转时间戳的方法:
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    
    NSTimeInterval _interval=[timeSp doubleValue];
    NSDate *date1 = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:type2];
     NSString *timestamp1 = [objDateformat stringFromDate: date1];
    
    return timestamp1;
}


/**
 时间转时间NSDate
 
 @param time1 时间1
 @param type1 时间1格式
 @return NSDate
 */
+(NSDate *)timeWithTime:(NSString *)time timeType:(NSString *)type;
{
    NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init] ;
    [formatter1 setDateStyle:NSDateFormatterMediumStyle];
    [formatter1 setTimeStyle:NSDateFormatterShortStyle];
    [formatter1 setDateFormat:type]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter1 setTimeZone:timeZone];
    
    NSDate* date = [formatter1 dateFromString:time];
    
    return date;
}


/**
 时间转时间戳

 @param timestamp 时间格式
 @return 时间
 */
+(NSString *)timetampWithTimes:(NSString *)time
{
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init] ;
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"]; // ----------设置你想要的格式,hh与HH的区别:分别表示12小时制,24小时制
    
    //设置时区,这个对于时间的处理有时很重要
    //例如你在国内发布信息,用户在国外的另一个时区,你想让用户看到正确的发布时间就得注意时区设置,时间的换算.
    //例如你发布的时间为2010-01-26 17:40:50,那么在英国爱尔兰那边用户看到的时间应该是多少呢?
    //他们与我们有7个小时的时差,所以他们那还没到这个时间呢...那就是把未来的事做了
    
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];
    [formatter setTimeZone:timeZone];
    
    NSDate* date = [formatter dateFromString:time]; //------------将字符串按formatter转成nsdate
    
//    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
//    
//    NSString *nowtimeStr = [formatter stringFromDate:datenow];//----------将nsdate按formatter格式转成nsstring
//    时间转时间戳的方法:
    NSString *timeSp = [NSString stringWithFormat:@"%ld", (long)[date timeIntervalSince1970]];
    NSLog(@"timeSp:%@",timeSp); //时间戳的值
    
//    时间戳转时间的方法
//    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:1296035591];
//    NSLog(@"1296035591  = %@",confromTimesp);
//    NSString *confromTimespStr = [formatter stringFromDate:confromTimesp];
//    NSLog(@"confromTimespStr =  %@",confromTimespStr);
//    时间戳转时间的方法:
//    NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
//    [formatter setDateStyle:NSDateFormatterMediumStyle];
//    [formatter setTimeStyle:NSDateFormatterShortStyle];
//    [formatter setDateFormat:@"yyyyMMddHHMMss"];
//    NSDate *date = [formatter dateFromString:@"1283376197"];
//    NSLog(@"date1:%@",date);
//    [formatter release];
    
    return timeSp;
}


/**
 //时间戳转时间
 
 @param timestamp 时间格式
 @return 时间今天。。，昨天。。等
 */
+(NSString *)timeWithTimestamp:(NSString *)timestamp
{
    //时间戳转时间
    
    
    
    NSTimeInterval _interval=[[self timetampWithTimes:timestamp] doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    NSDateFormatter *objDateformat = [[NSDateFormatter alloc] init];
    [objDateformat setDateFormat:@"yyyy-MM-dd HH:mm"];
    
    
    //处理
    NSDateFormatter *objDateformat1 = [[NSDateFormatter alloc] init];
    [objDateformat1 setDateFormat:@"yyyy-MM-dd"];
    NSString *timestamp1 = [objDateformat1 stringFromDate: date];
    //获取系统时间
    NSDate *currentDate = [NSDate date];
    //把时间格式化为HH:mm
    NSString *dateString = [objDateformat1 stringFromDate:currentDate];
    //今天
    if ([timestamp1 isEqualToString:dateString]) {
        [objDateformat1 setDateFormat:@"HH:mm"];
        timestamp1 = [NSString stringWithFormat:@"今天 %@",[objDateformat1 stringFromDate: date]];
    }
    
    else if ([self changtime:dateString] - [self changtime:timestamp1] == 1)
    {
        [objDateformat1 setDateFormat:@"HH:mm"];
        timestamp1 = [NSString stringWithFormat:@"昨天 %@",[objDateformat1 stringFromDate: date]];
    }else if ([self changtime:timestamp1] - [self changtime:dateString] > 365)
    {
        [objDateformat1 setDateFormat:@"yyyy-MM-dd HH:mm"];
        timestamp1 = [NSString stringWithFormat:@"%@",[objDateformat1 stringFromDate: date]];
    }
    else
    {
        [objDateformat1 setDateFormat:@"MM-dd HH:mm"];
        timestamp1 = [NSString stringWithFormat:@"%@",[objDateformat1 stringFromDate: date]];
    }
    
    return timestamp1;

}

/**
 //时间戳转时间

 @param timestamp 时间戳
 @param type NSDateFormatter类型
 @return NSString
 */
+(NSString *)timeWithTimestamp:(NSString *)timestamp timeType:(NSString *)type
{
    //时间戳转时间
    
    NSTimeInterval _interval=[timestamp doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:_interval];
    
    //处理
    NSDateFormatter *objDateformat1 = [[NSDateFormatter alloc] init];
    [objDateformat1 setDateFormat:type];
    NSString *timestamp1 = [objDateformat1 stringFromDate: date];
    
    
    return timestamp1;
    
}


/**
 事件处理

 @param string
 @return
 */
+(NSInteger )changtime:(NSString *)string
{
    NSArray *arr = [string componentsSeparatedByString:@"-"];
    
    return [[arr componentsJoinedByString:@""] integerValue];
}

/**
 *  压缩图片到指定文件大小
 *
 *  @param image 目标图片
 *  @param size  目标大小（最大值）
 *
 *  @return 返回的图片文件
 */
+(NSData *)scaleImage:(UIImage *)image toKb:(NSInteger)kb{
    
    if (!image) {
        return nil;
    }
    CGSize newSize = CGSizeMake(1000, 1000/image.size.width*image.size.height);
    
    UIGraphicsBeginImageContext(newSize);
    
//    image = [UIImage imageNamed:@"4.7_1680"];
    
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    
    if (kb<1) {
        return UIImageJPEGRepresentation(newImage, 1);
    }
    
    
    kb*=1024;
    
    
    
    CGFloat compression = 0.9f;
    CGFloat maxCompression = 0.1f;
    NSData *imageData = UIImageJPEGRepresentation(newImage, compression);
    NSLog(@"%ld",[imageData length]);
    while ([imageData length] > kb && compression > maxCompression) {
        compression -= 0.1;
        imageData = UIImageJPEGRepresentation(newImage, compression);
    }

    NSLog(@"%ld",[imageData length]);
    
    return imageData;
    
    
    
}
/**
 *  判断指定文件是否存在
 *
 *  @param fileName <#fileName description#>
 *
 *  @return <#return value description#>
 */
+ (BOOL)isExistFileInDocumentWithFileName:(NSString *)fileName
{
    NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    //文字路径
    NSString *filePath = [document stringByAppendingPathComponent:fileName];
    
    
    
    //判断文件是否存在
    return [[NSFileManager defaultManager] fileExistsAtPath:filePath];
}

/**
 *  资源文件的名字
 *
 *  @param urlString <#urlString description#>
 *
 *  @return <#return value description#>
 */
+ (NSString *)cacheFileNameWithUrlString:(NSString *)urlString
{
    
    NSString *filename = [NSString stringWithFormat:@"%@%@",[Helper md5String:urlString],[[urlString pathExtension] isEqualToString:@""] ? @"" : [NSString stringWithFormat:@".%@", [urlString pathExtension]]];
    
    NSLog(@"%@",filename);
    
    return filename;
}

/**
 *  删除指定文件
 *
 *  @param fileName <#fileName description#>
 *
 *  @return <#return value description#>
 */
+ (BOOL)removeFileInDocumentWithFileName:(NSString *)fileName
{
    NSString *document = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
    
    //文字路径
    NSString *filePath = [document stringByAppendingPathComponent:fileName];
    
    
    
    NSError *error = nil;
    
    //判断文件是否存在
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error];
        if (!error) {
            return YES;
        }
    }
    return NO;
}


/**
 //视频url转成MP4格式

 @param movUrl (NSURL *)movUrl
 @return NSURL
 */
+ (NSURL *)_convert2Mp4:(NSURL *)movUrl
{
    NSURL *mp4Url = nil;
    AVURLAsset *avAsset = [AVURLAsset URLAssetWithURL:movUrl options:nil];
    NSArray *compatiblePresets = [AVAssetExportSession exportPresetsCompatibleWithAsset:avAsset];

    if ([compatiblePresets containsObject:AVAssetExportPresetHighestQuality]) {
        AVAssetExportSession *exportSession = [[AVAssetExportSession alloc]initWithAsset:avAsset
                                                                              presetName:AVAssetExportPresetHighestQuality];
        mp4Url = [movUrl copy];
        mp4Url = [mp4Url URLByDeletingPathExtension];
        mp4Url = [mp4Url URLByAppendingPathExtension:@"mp4"];
        exportSession.outputURL = mp4Url;
        exportSession.shouldOptimizeForNetworkUse = YES;
        exportSession.outputFileType = AVFileTypeMPEG4;
        dispatch_semaphore_t wait = dispatch_semaphore_create(0l);
        [exportSession exportAsynchronouslyWithCompletionHandler:^{
            switch ([exportSession status]) {
                case AVAssetExportSessionStatusFailed: {
                    NSLog(@"failed, error:%@.", exportSession.error);
                } break;
                case AVAssetExportSessionStatusCancelled: {
                    NSLog(@"cancelled.");
                } break;
                case AVAssetExportSessionStatusCompleted: {
                    NSLog(@"completed.");
                } break;
                default: {
                    NSLog(@"others.");
                } break;
            }
            dispatch_semaphore_signal(wait);
        }];
        long timeout = dispatch_semaphore_wait(wait, DISPATCH_TIME_FOREVER);
        if (timeout) {
            NSLog(@"timeout.");
        }
        if (wait) {
            //dispatch_release(wait);
            wait = nil;
        }
    }

    return mp4Url;
}



/**
 //获取视屏时间的画面

 @param videoURL videoURL
 @param time 某时间画面
 @return UIImage
 */
+ (UIImage*) thumbnailImageForVideo:(NSURL *)videoURL atTime:(NSTimeInterval)time {


    

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:videoURL options:nil];
    NSParameterAssert(asset);
    AVAssetImageGenerator *assetImageGenerator =[[AVAssetImageGenerator alloc] initWithAsset:asset];
    assetImageGenerator.appliesPreferredTrackTransform = YES;
    assetImageGenerator.apertureMode = AVAssetImageGeneratorApertureModeEncodedPixels;

    CGImageRef thumbnailImageRef = NULL;
    CFTimeInterval thumbnailImageTime = time;
    NSError *thumbnailImageGenerationError = nil;
    thumbnailImageRef = [assetImageGenerator copyCGImageAtTime:CMTimeMake(thumbnailImageTime, 60)actualTime:NULL error:&thumbnailImageGenerationError];

    if(!thumbnailImageRef)
        NSLog(@"thumbnailImageGenerationError %@",thumbnailImageGenerationError);

    UIImage*thumbnailImage = thumbnailImageRef ? [[UIImage alloc]initWithCGImage: thumbnailImageRef] : nil;

    return thumbnailImage;
}





/**
 //将NSData转换成十六进制的字符串则可使用如下方式:

 @param data
 @return 
 */
+ (NSString *)convertDataToHexStr:(NSData *)data {
    if (!data || [data length] == 0) {
        return @"";
    }
    NSMutableString *string = [[NSMutableString alloc] initWithCapacity:[data length]];
    
    [data enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
        unsigned char *dataBytes = (unsigned char*)bytes;
        for (NSInteger i = 0; i < byteRange.length; i++) {
            NSString *hexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
            if ([hexStr length] == 2) {
                [string appendString:hexStr];
            } else {
                [string appendFormat:@"0%@", hexStr];
            }
        }
    }];
    
    return string;
}


/**
 处理webserwer服务器xml数据
 
 @param XMLstring xml数据
 @return 字符串数据数据
 */
//+(NSString *)handleXMLData:(NSString*)XMLstring
//{
//    GDataXMLDocument *doc = [[GDataXMLDocument alloc]initWithXMLString:XMLstring options:0 error:nil];
//    
//    GDataXMLElement *root = doc.rootElement;
//    
//    //获取子节点们；
//    //1.子节点的节点名
//    NSArray *ARR = [root elementsForName:@"soap:Body"];
//    
//    
//
//    //ARR数组里包含了三个节点，三个节点都是User节点；
//    
//    for (GDataXMLElement *element in ARR) {
//        
//        //每一个element是一个User节点；
//        
//        //获取当前节点下所有叫name的节点
//        NSArray *arrName = [element elementsForName:@"CRMInterfaceResponse"];
//        //获取name节点；
//        GDataXMLElement *name = arrName[0];
//        //获取name节点值；
//        NSString *data = name.stringValue;
//        
//        
//        
//        //数据处理
//        return data;
//        
//        
//    }
//    
//    return nil;
//
//}


/**
 根据时间类型获取今天时间

 @param formatter <#formatter description#>
 @return <#return value description#>
 */
+(NSString *)getTodayDateForFormatter:(NSString *)formatter
{
    NSDateFormatter *acceptDateformat = [[NSDateFormatter alloc] init];
    
    [acceptDateformat setDateFormat:formatter];
    
    //获取系统时间今天时间
    NSDate *currentDate = [NSDate date];
    

    NSString *nowDate = [acceptDateformat stringFromDate:currentDate];
    
    return nowDate;
    
}

/**
 判断是否是纯数字

 @param str str
 @return BOOL
 */
+ (BOOL) deptNumInputShouldNumber:(NSString *)str;
{
    NSString *regex = @"[0-9]*";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    if ([pred evaluateWithObject:str]) {
        return YES;
    }
    return NO;
}
/**
 带有中文的转换
 
 @param urlString 图片url地址及
 @param imageType nil默认mid_image
 @return 转化后
 */
+(NSString *)imageUrlStringToChinese:(NSString *)urlString imageType:(NSString *)imageType
{
    imageType = imageType?imageType:mid_image;
    
    NSString *urlStr = [NSString stringWithFormat:@"%@%@",urlString,imageType];
    urlStr=[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    return urlString;
    
}

/**
 根据生日获取年龄

 @param birth
 @return 
 */
+(NSInteger)getAgeWithBirth:(NSString *)birth{
    
    NSDateFormatter *dateFomatter = [[NSDateFormatter alloc] init];
    
    dateFomatter.dateFormat = @"yyyy-MM-dd";
    
    // 截止时间data格式
    NSDate *expireDate = [dateFomatter dateFromString:birth];
    
    // 当前时间data格式
    NSDate *nowDate = [NSDate date];
    // 当前日历
    NSCalendar *calendar = [NSCalendar currentCalendar];
    // 需要对比的时间数据
    NSCalendarUnit unit = NSCalendarUnitYear | NSCalendarUnitMonth
    | NSCalendarUnitDay | NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond;
    // 对比时间差
    NSDateComponents *dateCom = [calendar components:unit fromDate:expireDate toDate:nowDate options:0];
    
    return dateCom.year;
    
    
}

/**
 特定时间跟当前时间比较
 
 @return 返回间隔s 大于0将来，小于0过去
 */
+ (NSTimeInterval )timeComperCurTimesetDateFormat:(NSString *)format time:(NSString *)time
{
    
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    
    [dateFormatter1 setDateFormat:format];
    
    
    
    
    NSDate *date1 = [dateFormatter1 dateFromString:time];
    
    
    //获取系统时间今天时间
    //获取系统时间今天时间
    NSDate *currentDate = [NSDate date];
    
    
    //计算约定时间跟当前时间间隔s
    NSTimeInterval timeBetween = [date1 timeIntervalSinceDate:currentDate];
    
    return timeBetween;
    
}

/**
 特定时间1跟特定时间2
 
 @return 返回间隔s 大于0将来，小于0过去
 */

+ (NSTimeInterval )timeComperCurTimesetDateFormat:(NSString *)format time1:(NSString *)time1  time2:(NSString *)time2
{
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc] init];
    [dateFormatter1 setDateFormat:format];
    
    
    
    
    NSDate *date1 = [dateFormatter1 dateFromString:time1];
    
    NSDate *date2 = [dateFormatter1 dateFromString:time2];
    
    
    
    //计算约定时间跟当前时间间隔s
    NSTimeInterval timeBetween = [date1 timeIntervalSinceDate:date2];
    
    return timeBetween;
    
}

/**
 *  根据月和日的下标获取星座名(未添加日期判错处理)
 *
 *  @param monthIndex 月的下标[0-11]
 *  @param dayIndex   日的下标[0-27,28,29,30]
 *
 *  @return 星座名
 */
+ (NSString *)getConstellationNameByMonthIndex:(NSInteger)monthIndex dayIndex:(NSInteger)dayIndex {
//    NSArray *constellations = @[@"水瓶座", @"双鱼座", @"白羊座", @"金牛座", @"双子座", @"巨蟹座", @"狮子座", @"处女座", @"天秤座", @"天蝎座", @"射手座", @"摩羯座"];
//    NSInteger index;
//    NSArray *conIndexs = @[@(20),@(19),@(21),@(20),@(21),@(22),@(23),@(23),@(23),@(24),@(23),@(22)];
//    if ([[conIndexs objectAtIndex:monthIndex] integerValue] <= dayIndex + 1) {
//        index = monthIndex;
//    } else index = (monthIndex - 1 + 12) % 12;
//    return [constellations objectAtIndex:index];
    
    NSString *astroString = @"魔羯水瓶双鱼白羊金牛双子巨蟹狮子处女天秤天蝎射手魔羯";
    NSString *astroFormat = @"102123444543";
    NSString *result;
    
    if (monthIndex<1||monthIndex>12||dayIndex<1||dayIndex>31){
        return @"未知星座";
    }
    
    if(monthIndex==2 && dayIndex>29)
    {
        return @"未知星座";
    }else if(monthIndex==4 || monthIndex==6 || monthIndex==9 || monthIndex==11) {
        
        if (dayIndex>30) {
            return @"未知星座";
        }
    }
    
    result=[NSString stringWithFormat:@"%@座",[astroString substringWithRange:NSMakeRange(monthIndex*2-(dayIndex < [[astroFormat substringWithRange:NSMakeRange((monthIndex-1), 1)] intValue] - (-19))*2,2)]];
    return result;

}


//#####2. 获取设备版本号


+ (NSString *)getDeviceName {
    
    // 需要#import "sys/utsname.h"
    
    struct utsname systemInfo;
    
    uname(&systemInfo);
    
    NSString *deviceString = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding];
    
    
    
    if ([deviceString isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    
    if ([deviceString isEqualToString:@"iPhone3,2"])    return @"iPhone 4";
    
    if ([deviceString isEqualToString:@"iPhone3,3"])    return @"iPhone 4";
    
    if ([deviceString isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    
    if ([deviceString isEqualToString:@"iPhone5,1"])    return @"iPhone 5";
    
    if ([deviceString isEqualToString:@"iPhone5,2"])    return @"iPhone 5 (GSM+CDMA)";
    
    if ([deviceString isEqualToString:@"iPhone5,3"])    return @"iPhone 5c (GSM)";
    
    if ([deviceString isEqualToString:@"iPhone5,4"])    return @"iPhone 5c (GSM+CDMA)";
    
    if ([deviceString isEqualToString:@"iPhone6,1"])    return @"iPhone 5s (GSM)";
    
    if ([deviceString isEqualToString:@"iPhone6,2"])    return @"iPhone 5s (GSM+CDMA)";
    
    if ([deviceString isEqualToString:@"iPhone7,1"])    return @"iPhone 6 Plus";
    
    if ([deviceString isEqualToString:@"iPhone7,2"])    return @"iPhone 6";
    
    if ([deviceString isEqualToString:@"iPhone8,1"])    return @"iPhone 6s";
    
    if ([deviceString isEqualToString:@"iPhone8,2"])    return @"iPhone 6s Plus";
    
    if ([deviceString isEqualToString:@"iPhone8,4"])    return @"iPhone SE";
    
    
    
    if ([deviceString isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    
    if ([deviceString isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    
    if ([deviceString isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    
    if ([deviceString isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    
    if ([deviceString isEqualToString:@"iPod5,1"])      return @"iPod Touch (5 Gen)";
    
    
    
    if ([deviceString isEqualToString:@"iPad1,1"])      return @"iPad";
    
    if ([deviceString isEqualToString:@"iPad1,2"])      return @"iPad 3G";
    
    if ([deviceString isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    
    if ([deviceString isEqualToString:@"iPad2,2"])      return @"iPad 2";
    
    if ([deviceString isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    
    if ([deviceString isEqualToString:@"iPad2,4"])      return @"iPad 2";
    
    if ([deviceString isEqualToString:@"iPad2,5"])      return @"iPad Mini (WiFi)";
    
    if ([deviceString isEqualToString:@"iPad2,6"])      return @"iPad Mini";
    
    if ([deviceString isEqualToString:@"iPad2,7"])      return @"iPad Mini (GSM+CDMA)";
    
    if ([deviceString isEqualToString:@"iPad3,1"])      return @"iPad 3 (WiFi)";
    
    if ([deviceString isEqualToString:@"iPad3,2"])      return @"iPad 3 (GSM+CDMA)";
    
    if ([deviceString isEqualToString:@"iPad3,3"])      return @"iPad 3";
    
    if ([deviceString isEqualToString:@"iPad3,4"])      return @"iPad 4 (WiFi)";
    
    if ([deviceString isEqualToString:@"iPad3,5"])      return @"iPad 4";
    
    if ([deviceString isEqualToString:@"iPad3,6"])      return @"iPad 4 (GSM+CDMA)";
    
    if ([deviceString isEqualToString:@"iPad4,1"])      return @"iPad Air (WiFi)";
    
    if ([deviceString isEqualToString:@"iPad4,2"])      return @"iPad Air (Cellular)";
    
    if ([deviceString isEqualToString:@"iPad4,4"])      return @"iPad Mini 2 (WiFi)";
    
    if ([deviceString isEqualToString:@"iPad4,5"])      return @"iPad Mini 2 (Cellular)";
    
    if ([deviceString isEqualToString:@"iPad4,6"])      return @"iPad Mini 2";
    
    if ([deviceString isEqualToString:@"iPad4,7"])      return @"iPad Mini 3";
    
    if ([deviceString isEqualToString:@"iPad4,8"])      return @"iPad Mini 3";
    
    if ([deviceString isEqualToString:@"iPad4,9"])      return @"iPad Mini 3";
    
    if ([deviceString isEqualToString:@"iPad5,1"])      return @"iPad Mini 4 (WiFi)";
    
    if ([deviceString isEqualToString:@"iPad5,2"])      return @"iPad Mini 4 (LTE)";
    
    if ([deviceString isEqualToString:@"iPad5,3"])      return @"iPad Air 2";
    
    if ([deviceString isEqualToString:@"iPad5,4"])      return @"iPad Air 2";
    
    if ([deviceString isEqualToString:@"iPad6,3"])      return @"iPad Pro 9.7";
    
    if ([deviceString isEqualToString:@"iPad6,4"])      return @"iPad Pro 9.7";
    
    if ([deviceString isEqualToString:@"iPad6,7"])      return @"iPad Pro 12.9";
    
    if ([deviceString isEqualToString:@"iPad6,8"])      return @"iPad Pro 12.9";
    
    
    
    if ([deviceString isEqualToString:@"i386"])         return @"Simulator";
    
    if ([deviceString isEqualToString:@"x86_64"])       return @"Simulator";
    
    
    
    return deviceString;
    
}


//#####3. 获取iPhone名称


/// 获取iPhone名称

+ (NSString *)getiPhoneName {
    
    return [UIDevice currentDevice].name;
    
}





/// 获取app版本号

+ (NSString *)getAPPVerion {
    
    return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
}

//#####8. 获取通用的唯一识别码UUID


/// 通用唯一识别码UUID

+ (NSString *)getUUID {
    
    return [[UIDevice currentDevice] identifierForVendor].UUIDString;
    
}



/// 当前系统版本号

+ (NSString *)getSystemVersion {
    
    return [UIDevice currentDevice].systemVersion;
    
}


#pragma mark 生成image
+ (UIImage *)makeImageWithView:(UIView *)view withSize:(CGSize)size
{
    
    // 下面方法，第一个参数表示区域大小。第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。第三个参数就是屏幕密度了，关键就是第三个参数 [UIScreen mainScreen].scale。
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [view.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}

#pragma mark/ 将富文本格式化为超文本 */
+(NSString *)htmlStringByHtmlAttributeString:(NSAttributedString *)htmlAttributeString{
    NSString *htmlString;
    NSDictionary *exportParams = @{NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
    
    NSData *htmlData = [htmlAttributeString dataFromRange:NSMakeRange(0, htmlAttributeString.length) documentAttributes:exportParams error:nil];
    
    htmlString = [[NSString alloc] initWithData:htmlData encoding: NSUTF8StringEncoding];
    
    return htmlString;
}

#pragma mark//** 将超文本格式化为富文本 */

+(NSAttributedString *)htmlAttributeStringByHtmlString:(NSString *)htmlString{
    
    
    
    NSAttributedString *attributeString;
    NSData *htmlData = [htmlString dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *importParams = @{NSDocumentTypeDocumentAttribute:NSHTMLTextDocumentType,NSCharacterEncodingDocumentAttribute:[NSNumber numberWithInt:NSUTF8StringEncoding]};
    NSError *error = nil;
    attributeString = [[NSAttributedString alloc] initWithData:htmlData options:importParams documentAttributes:NULL error:&error];
    return attributeString;
}

@end
